package com.tanhua.manager.service;

import cn.hutool.core.date.DateTime;
import com.tanhua.domain.db.Freeze;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.Video;
import com.tanhua.domain.vo.MovementsVo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VideoVo;
import com.tanhua.dubbo.api.db.FreezeApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.VideoApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManageService {


    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private MovementApi movementApi;
    @Autowired
    private StringRedisTemplate redisTemplate;



    public ResponseEntity queryUsers(Integer page, Integer pagesize, Long id, String nickname, String city) {

        PageResult pageResult = userInfoApi.queryUsers(page,pagesize,id,nickname,city);

        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryUserInfo(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity queryUserMessages(Integer page, Integer pagesize, Long userId, Integer state) {
        PageResult pageResult =  movementApi.queryUserMovements(page,pagesize,userId,state);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();
        List<MovementsVo> movementVoList = new ArrayList<>();
        for (Movement movement : movementList) {
            UserInfo userInfo = userInfoApi.findById(movement.getUserId());
            MovementsVo movementsVo = movementAndUserInfoToMovementVo(movement, userInfo);
            movementVoList.add(movementsVo);
        }
        pageResult.setItems(movementVoList);
        return ResponseEntity.ok(pageResult);
    }

    public MovementsVo movementAndUserInfoToMovementVo(Movement movement, UserInfo userInfo) {
        //            把UserInfo的内容放到MovementVo
        MovementsVo movementsVo = new MovementsVo();
        BeanUtils.copyProperties(userInfo,movementsVo);
        movementsVo.setUserId(userInfo.getId());
        if(userInfo.getTags()!=null){
            movementsVo.setTags(userInfo.getTags().split(","));
        }
        //            把Movement的内容放到MovementVo
        BeanUtils.copyProperties(movement,movementsVo);
        movementsVo.setId(movement.getId().toString());//动态id //注意这个的id需要手动赋值
        movementsVo.setImageContent(movement.getMedias().toArray(new String[]{})); //集合转成字符串数据
        movementsVo.setDistance("500米以内"); //先随便给一个值

        //        这里有个坑 API文档上要的是一个Integer数字 但是这里要的是一个字符串 "yyyy-MM-dd HH:mm"
        movementsVo.setCreateDate(new DateTime(movement.getCreated()).toString("yyyy-MM-dd HH:mm"));


        return movementsVo;
    }


    public ResponseEntity passUserMessages(List<String> ids, Integer state) {
        Map<String,String> map=new HashMap<>();
        movementApi.findByMovementId(ids, state);
        map.put("message", "审核通过");
        return ResponseEntity.ok(map);

    }

    public ResponseEntity rejectUserMessages(List<String> ids, Integer state) {
        Map<String, String> map = new HashMap<>();
        movementApi.findByMovementId2(ids, state);
        map.put("messages", "审核被拒绝");
        return ResponseEntity.ok(map);
    }





    //
    @DubboReference
    private FreezeApi freezeApi;
    public ResponseEntity usersFreeze(Freeze freeze) {
        if (StringUtils.isNotBlank(redisTemplate.boundValueOps("FREEZE_" + freeze.getUserId() + "_").get())) {
            String message = "用户已被冻结";
            Map<String, String> map = new HashMap<>();
            map.put("message", message);
            return ResponseEntity.ok(map);
        }
        freezeApi.save(freeze);
        UserInfo userInfo = userInfoApi.queryUserInfoById(freeze.getUserId());
        userInfo.setId(freeze.getUserId());
        userInfo.setUserStatus("2");

        userInfoApi.update(userInfo);
        Integer day = 0;
        if (freeze.getFreezingTime() == 1) {
            day = 1;
            redisTemplate.boundValueOps("FREEZE_" + freeze.getUserId() + "_").set("ONE", day, TimeUnit.DAYS);
        }
        if (freeze.getFreezingTime() == 2) {
            day = 3;
            redisTemplate.boundValueOps("FREEZE_" + freeze.getUserId() + "_").set("THREE", day, TimeUnit.DAYS);
        }
        if (freeze.getFreezingTime() == 3) {
            redisTemplate.boundValueOps("FREEZE_" + freeze.getUserId() + "_").set("SEVEN");
        }
        String message = "操作成功";
        Map<String, String> map = new HashMap<>();
        map.put("message", message);
        return ResponseEntity.ok(map);
    }


    public ResponseEntity usersUnfreeze(Freeze freeze) {
        Long userId = freeze.getUserId();
        String userFreeze = redisTemplate.boundValueOps("FREEZE_" + freeze.getUserId() + "_").get();
        if (StringUtils.isBlank(userFreeze)) {
            String message = "用户未被冻结";
            Map<String, String> map = new HashMap<>();
            map.put("message", message);
            return ResponseEntity.ok(map);
        }
        redisTemplate.delete("FREEZE_" + userId + "_");
        UserInfo userInfo = userInfoApi.queryUserInfoById(freeze.getUserId());

        freezeApi.findByIddelete(userId);
        userInfo.setId(freeze.getUserId());
        userInfo.setUserStatus("1");

        userInfoApi.update(userInfo);
        String message = "操作成功";
        Map<String, String> map = new HashMap<>();
        map.put("message", message);
        return ResponseEntity.ok(map);
    }

    @DubboReference
    private VideoApi videoApi;

    public ResponseEntity queryUserVideo(Integer page, Integer pagesize, Long userId) {

        PageResult pageResult =  videoApi.queryVideoList(page,pagesize,userId);
        List<Video> items = (List<Video>) pageResult.getItems();
        //        Video--> VideoVo
        //       把Video转成 VideoVo
        List<VideoVo> list = new ArrayList<>();

        UserInfo userInfo = userInfoApi.findById(userId);
        for (Video video : items) {
            VideoVo videoVo = new VideoVo();

            //            把 video+userInfo ---》videoVo
            BeanUtils.copyProperties(video,videoVo);

            videoVo.setId(video.getId().toString());
            videoVo.setCover(video.getPicUrl());
            videoVo.setSignature(video.getText());

            BeanUtils.copyProperties(userInfo,videoVo);
            videoVo.setUserId(userInfo.getId());
            list.add(videoVo);
        }

        pageResult.setItems(list);
        return ResponseEntity.ok(pageResult);

    }
}
